<template>
    <div class="input-upload ivu-upload ivu-upload-drag" :class="{'ivu-upload-dragOver':dragOver,'ivu-upload-small':size==='small'}" @click="handleClick" @drop.prevent="onDrop" @dragover.prevent="dragOver = true" @dragleave.prevent="dragOver = false">
        <input v-if="inputFile" :multiple="multiple?'multiple':false" ref="input" :name="name" @change="fileChange" type="file" class="ivu-upload-input">
        <div class="upload-box" v-if="!fileName">
            <Icon class="upload-icon" type="ios-cloud-upload"></Icon>
            <p class="upload-tip">点击或将文件拖拽到这里上传</p>
        </div>
        <div class="upload-box" v-else>
            <Icon class="icon-file upload-icon" type="document-text"></Icon>
            <p>{{fileName}}</p>
        </div>
    </div>
</template>
<script>
//计数标记，作为自增id防止重复
var counter = 0;
export default {
  props: {
    name: {},
    size: {},
    multiple: {},
    noAction: {}
  },
  data() {
    return {
      fileName: null,
      id: null,
      value: null,
      dragOver: false,
      inputFile: true
    };
  },
  created() {
    this.id = "input_upload_" + counter++;
  },
  mounted() {
    this.$input = this.$refs.input;
    this.$set(this, "value", this.$refs.input);
    //this.value = this.$refs.input
  },
  methods: {
    handleClick() {
      if (!this.inputFile) {
        this.inputFile = true;
        this.$nextTick(() => {
          this.$refs.input.click();
        });
      } else {
        this.$refs.input.click();
      }
    },
    fileChange(v) {
      this.$emit("fileUpload", v.target.files);
      if (this.noAction) return;
      this.fileName = v.target.value;
      this.$set(this, "value", this.$refs.input);
      this.$emit("fileChange", v);
      this.$emit("input", this.value);
    },
    onDrop(e) {
      this.$emit("fileUpload", e.dataTransfer.files);
      if (this.noAction) return;
      this.dragOver = false;
      this.fileName = e.dataTransfer.files[0].name;
      this.file = e.dataTransfer.files[0];
      this.inputFile = false;
    }
  }
};
</script>
<style lang="less">
.input-upload {
  > div {
    padding: 20px 0px;
  }
  .ivu-icon {
    font-size: 52px;
    color: rgb(51, 153, 255);
    &.icon-file {
      color: #495060;
    }
  }
  &.ivu-upload-small {
    height: 100%;
    .upload-icon {
      font-size: 36px;
    }
    .upload-box {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .upload-tip {
      display: none;
    }
  }
}

label.ivu-upload {
  display: block;
}
</style>
